var url = require('url');
var lodash = require('lodash');
var promiseRequest = require('promise-request');
var config = require('./../../config');

var host = process.env.app_host || config.app.appUrl;
console.log(host)
var config = lodash.pick(url.parse(host), ['protocol', 'hostname', 'port']);
config.scheme = config.protocol;
config.deserialize = function(s) {
  if (!s) return [];
  return JSON.parse(s);
}
process.on('uncaughtException', function(err) {
  console.error(err.stack || err);
});

function requestApi(method, storeId, path, data, options) {
  var url = '/api/stores/' + storeId + path;
  return promiseRequest(lodash.extend({
    path: url,
    method: method,
    headers: {
      token: "V0VJWElOOiQqJTp3ZWl4aW4xMjM0NTZAIyQ="
    }
  }, config), data);
}
var appApi = function(storeId) {
  return {
    request: function(method, path, data, options) {
      return promiseRequest(lodash.extend({
        path: '/api' + path,
        method: method
      }, config, {
        headers: {
          token: "V0VJWElOOiQqJTp3ZWl4aW4xMjM0NTZAIyQ="
        }
      }), data);
    },
    get: function(path) {
      return requestApi('GET', storeId, path, null);
    },
    put: function(path, data) {
      return requestApi('PUT', storeId, path, data, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          token: "V0VJWElOOiQqJTp3ZWl4aW4xMjM0NTZAIyQ=",
          'Content-Length': 200
        }
      });

    },
    post: function(path, data) {
      return requestApi('post', storeId, path, data, {
        headers: {
          'Content-Type': 'application/json'
        }
      });
    },
    delete: function(path) {
      return requestApi('DELETE', storeId, path);
    },
    getUrl: function(path) {
      return host + '/api' + path;
    }
  };
}
appApi.forwardError = function(res) {
  return function(error) {
    if (!error.statusCode)
      console.log(error.stack || error)
    if (error instanceof Error) {
      error = {
        name: error.name,
        message: error.message
      };
    }
    if (!error.statusCode) {
      return res.status(500).json(error);
    }
    // console.error(error);
    res.status(error.statusCode).send(error.statusMessage);
    //  res.render('error', { error: err.statusMessage });
  }
}
module.exports = appApi;
